<template>
    <el-cascader 
        ref="role"
        v-model="roleValue" 
        :placeholder="placeholder" 
        :options="options" 
        :props="defaultProps"
        :disabled="disabled" 
        :clearable="clearable" 
        :show-all-levels="showAllLevels"
        @change="closePanel"></el-cascader>
</template>
<script>
    import { getRoleTree, getRoleQueryAuth } from "@/service/core/roleConf";
    import { transformTozTreeFormat } from "@/utils/Tools";
    export default {
        name: 'selectRole', // 角色选择下拉框（支持单选、多选）
        props: {
            value: { // v-model绑定值
                type: [String, Array],
                default() {
                    if (this.multiple) {
                        return []
                    } else {
                        return '';
                    }
                }
            },
            label: { // 角色名称
                type: [String, Array],
                default() {
                    if (this.multiple) {
                        return []
                    } else {
                        return ''
                    }
                }
            },
            multiple: { // 是否多选
                type: Boolean,
                default: false
            },
            disabled: { // 是否禁用
                type: Boolean,
                default: false,
            },
            clearable: { // 是否可清楚
                type: Boolean,
                default: true
            },
            checkStrictly: { // 是否父子节点不关联
                type: Boolean,
                default: true
            },
            showAllLevels: { // 是否展示全路径
                type: Boolean,
                default: false
            },
            placeholder: String,
        },
        data() {
            return {
                options: [],
            };
        },
        watch: {
            value(val) {
                if (!this.multiple) {
                    if (!val) {
                        this.roleName = '';
                    }
                } else {
                    if (val.length == 0) {
                        this.roleName = [];
                    }
                }
            },
        },
        created() {
            this.treeDataInit();
        },
        computed: {
            roleValue: {
                get: function () {
                    if (this.multiple) {
                        if(this.value.length) {
                            let path = this.value.map(item => {
                                let arr = this.getPathByKey(item, 'value', this.options) || [];
                                return arr.map(v => v.value)
                            })
                            if(path.length) { // 获取label值
                                this.roleName = path.map(item2 => {
                                    let arr2 = this.getPathByKey(item2[item2.length - 1], 'value', this.options) || [];
                                    if(arr2.length) {
                                        return arr2[arr2.length - 1].label
                                    }
                                })
                            }
                            return path
                        }else {
                            this.roleName = [];
                            return []
                        }
                    } else {
                        if (this.value) {
                            let path = this.getPathByKey(this.value, 'value', this.options) || [];
                            if(path.length) { // 获取label值
                                this.roleName = path[path.length - 1].label;
                            }else {
                                this.roleName = '';
                            }
                            return path.map(v => v.value);
                        } else {
                            this.roleName = '';
                            return []
                        }
                    }
                },
                set: function (val) {
                    if (this.multiple) {
                        if (val.length) {
                            let result = val.map(item => {
                                return item[item.length - 1]
                            })
                            this.$emit('input', result);
                        } else {
                            this.$emit('input', val);
                        }
                    } else {
                        if (val.length) {
                            this.$emit('input', val[val.length - 1]);
                        } else {
                            this.$emit('input', '');
                        }
                    }

                }
            },
            roleName: {
                get: function () {
                    return this.label
                },
                set: function (val) {
                    this.$emit("update:label", val);
                }
            },
            defaultProps() { // 组件属性
                return {
                    checkStrictly: this.checkStrictly,
                    multiple: this.multiple,
                }
            }
        },
        methods: {
            treeDataInit() {
                let params = {};
                getRoleQueryAuth(params).then(res => {
                    if (res.data.code == 1000) {
                        let data = res.data.data;
                        if (Array.isArray(data) && data.length > 0) {
                            data = data.map(item => {
                                return {
                                    id: item.id,
                                    pId: item.pId,
                                    label: item.name,
                                    value: item.id,
                                }
                            })
                            this.options = [...data];
                        }
                    }
                });
            },
            getPathByKey(value, key, arr) { // 获取path 返回节点集合
                let temppath = [];
                try {
                    function getNodePath(node) {
                        temppath.push(node);
                        //找到符合条件的节点，通过throw终止掉递归
                        if (node[key] === value) {
                            throw ("GOT IT!");
                        }
                        if (node.children && node.children.length > 0) {
                            for (var i = 0; i < node.children.length; i++) {
                                getNodePath(node.children[i]);
                            }
                            //当前节点的子节点遍历完依旧没找到，则删除路径中的该节点
                            temppath.pop();
                        }
                        else {
                            //找到叶子节点时，删除路径当中的该叶子节点
                            temppath.pop();
                        }
                    }
                    for (let i = 0; i < arr.length; i++) {
                        getNodePath(arr[i]);
                    }
                } catch (e) {
                    return temppath;
                }
            },
            closePanel(value) { // 单选模式下 选中数据关闭下拉面板
                if(!this.multiple) {
                    if(this.$refs.role) {
                        this.$refs.role.toggleDropDownVisible(false);
                    }
                }
            },
        }
    };
</script>